import argparse
from datetime import datetime
import platform
import subprocess
import os
import sys

import Config

# # 设置到期日期（年-月-日）
# EXPIRATION_DATE = "2025-12-31"
#
# def check_license():
#     now = datetime.now()
#     expire = datetime.strptime(EXPIRATION_DATE, "%Y-%m-%d")
#     if now > expire:
#         print(f"程序已过期，使用期限到 {EXPIRATION_DATE}")
#         sys.exit(1)  # 退出程序

def get_maven_executable():
    """根据系统返回 Maven 可执行文件路径"""
    if platform.system() == "Windows":
        mvn_exe = os.path.join(Config.MAVEN_HOME, "bin", "mvn.cmd")
    else:
        mvn_exe = os.path.join(Config.MAVEN_HOME, "bin", "mvn")
    if not os.path.exists(mvn_exe):
        raise FileNotFoundError(f"[ERROR] Maven executable not found at {mvn_exe}")
    return mvn_exe

def run_maven_clean_compile(project_path):
    """执行 mvn clean compile"""
    print("[INFO] Running Maven clean compile...")
    abs_project_path = os.path.abspath(project_path)
    print(f"[DEBUG] Project path: {abs_project_path}")

    pom_path = os.path.join(abs_project_path, "pom.xml")
    if not os.path.exists(pom_path):
        raise FileNotFoundError(f"[ERROR] pom.xml not found at {pom_path}")

    mvn_executable = get_maven_executable()
    cmd = [mvn_executable, "clean", "compile", "-Drat.skip=true"]
    print("[DEBUG] Executing:", " ".join(cmd))

    try:
        result = subprocess.run(
            cmd,
            cwd=abs_project_path,
            check=True,
            capture_output=True,
            text=True
        )
        print("[INFO] ✅ Maven clean compile completed successfully")
        if result.stdout:
            print("[DEBUG] Maven output:", result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"[ERROR] Maven clean compile failed with exit code {e.returncode}")
        if e.stdout:
            print("[DEBUG] Maven stdout:", e.stdout)
        if e.stderr:
            print("[ERROR] Maven stderr:", e.stderr)
        raise

def run_maven_copy_dependencies(project_path):
    """执行 mvn dependency:copy-dependencies"""
    print("[INFO] Running Maven dependency:copy-dependencies...")
    abs_project_path = os.path.abspath(project_path)

    mvn_executable = get_maven_executable()
    cmd = [mvn_executable, "dependency:copy-dependencies"]
    print("[DEBUG] Executing:", " ".join(cmd))

    try:
        result = subprocess.run(
            cmd,
            cwd=abs_project_path,
            check=True,
            capture_output=True,
            text=True
        )
        print("[INFO] ✅ Maven dependency:copy-dependencies completed successfully")
        if result.stdout:
            print("[DEBUG] Maven output:", result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"[ERROR] Maven clean compile failed with exit code {e.returncode}")
        if e.stdout:
            print("[DEBUG] Maven stdout:", e.stdout)
        if e.stderr:
            print("[ERROR] Maven stderr:", e.stderr)
        raise

def run_ckg(project_path):
    print("[INFO] Running CKGConstruction...")

    jar_path = Config.CKGConstruction_Jar_Path
    if not os.path.exists(jar_path):
        raise FileNotFoundError(f"[ERROR] JAR not found at {jar_path}")

    cmd = [
        "java", "-jar", jar_path,
        "-p", project_path,
        "-u", Config.Neo4j_URI,
        "-n", Config.Neo4j_User,
        "-w", Config.Neo4j_Password,
        "-j", Config.JAVA_VERSION,
        "-cp", Config.JAVA_HOME,
    ]
    print("[DEBUG] Executing:", " ".join(cmd))
    subprocess.run(cmd, check=True)

def main():
    # check_license()
    Config.load_config()
    from EnvironmentService import EnvironmentService
    parser = argparse.ArgumentParser(description="TestAgent CLI")
    parser.add_argument("-p", "--project", required=True, help="Path to the project under test")
    args = parser.parse_args()

    envServer = EnvironmentService()
    envServer.set_base_path(args.project)

    run_maven_clean_compile(args.project)
    run_maven_copy_dependencies(args.project)

    # Step 1: 构建知识图谱
    print("[INFO] Constructing knowledge graph...")
    run_ckg(args.project)

    import _1_GenerationProcess as gen

    # Step 2: 生成测试用例
    print("[INFO] Running Generation Process...")
    gen.run_generation(args.project)


    print("[INFO] ✅ All processes completed successfully.")

if __name__ == "__main__":
    main()
